#include <database.h>
#include <map.h>
#include <critical.h>
#include <stdio.h>

smap *gm = NULL;
static critical cs;

void db_init()
{
    if( gm == NULL )
    {
        init_critical( &cs );
        gm = sm_create();
    }
}

void db_uninit()
{
    if( gm != NULL )
    {
        sm_destroy( gm );
        gm = NULL;
        destroy_critical( &cs );
    }
}

int db_insert( const char *key, void *val )
{
    void *t;
    enter_critical( &cs );
    if( -1 == sm_find( gm, key, &t ) )
    {
        sm_insert( gm, key, val );
        leave_critical( &cs );
        return 0;
    }
    leave_critical( &cs );
    return -1;
}

int db_update( const char *key, void *val )
{
    void *t;
    enter_critical( &cs );
    if( 0 == sm_find( gm, key, &t ) )
    {
        sm_insert( gm, key, val );
        leave_critical( &cs );
        return 0;
    }
    leave_critical( &cs );
    return -1;
}

int db_query( const char *key, void **val )
{
    int r;
    enter_critical( &cs );
    r = sm_find( gm, key, val );
    leave_critical( &cs );
    return r;
}

int db_delete( const char *key )
{
    void *t;
    enter_critical( &cs );
    if( 0 == sm_find( gm, key, &t ) )
    {
        sm_delete( gm, key );
        leave_critical( &cs );
        return 0;
    }
    leave_critical( &cs );
    return -1;
}

